package com.alks.common.utils.excelUtils.nestExcel.handler;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alks.common.utils.excelUtils.nestExcel.entity.ExportEntity;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: chen
 * @date: 2024/11/14
 * @description: EasyExcel自适应列宽
 */
public class AutoWidthCellWriteHandler extends AbstractColumnWidthStyleStrategy {

	private Map<Integer, Map<Integer, Integer>> cache = new HashMap<>();

	private final Integer width = 255;

	private int skipLine; // 跳过自适应宽度的行数

	public AutoWidthCellWriteHandler(int skipLine) {
		this.skipLine = skipLine;
	}

	@Override
	protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
		if (relativeRowIndex < skipLine) return;
		boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
		int num = 100000;
		if (needSetWidth) {
			Map<Integer, Integer> maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo());
			if (maxColumnWidthMap == null) {
				maxColumnWidthMap = new HashMap<Integer, Integer>((int) (num/0.75+1.0));
				cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
			}

			Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
			if (columnWidth >= 0) {
				if (columnWidth > width) {
					columnWidth = width;
				}

				Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
				if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
					maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
					writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
				}

			}
		}
	}


	private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
		if (isHead) {
			return cell.getStringCellValue().getBytes().length;
		} else {
			WriteCellData cellData = cellDataList.get(0);
			CellDataTypeEnum type = cellData.getType();
			if (type == null) {
				return -1;
			} else {
				switch (type) {
					case STRING:
						return cellData.getStringValue().getBytes().length + 1;
					case BOOLEAN:
						return cellData.getBooleanValue().toString().getBytes().length + 1;
					case NUMBER:
						return cellData.getNumberValue().stripTrailingZeros().toString().getBytes().length + 1;
					default:
						return -1;
				}
			}
		}
	}
}